import { Controller, Get, Param, Res, NotFoundException } from '@nestjs/common';
import { Response } from 'express';
import { readFile } from 'fs/promises';
import { join } from 'path';
import { existsSync } from 'fs';

@Controller('uploads')
export class StaticFilesController {
  @Get('images/:filename')
  async serveImage(@Param('filename') filename: string, @Res() res: Response) {
    const imagePath = join(process.cwd(), 'uploads', 'images', filename);
    
    if (!existsSync(imagePath)) {
      throw new NotFoundException('图片文件不存在');
    }

    try {
      const imageBuffer = await readFile(imagePath);
      const ext = filename.split('.').pop()?.toLowerCase();
      
      let contentType = 'image/jpeg';
      switch (ext) {
        case 'png':
          contentType = 'image/png';
          break;
        case 'gif':
          contentType = 'image/gif';
          break;
        case 'webp':
          contentType = 'image/webp';
          break;
        case 'svg':
          contentType = 'image/svg+xml';
          break;
        default:
          contentType = 'image/jpeg';
      }

      res.setHeader('Content-Type', contentType);
      res.setHeader('Cache-Control', 'public, max-age=31536000'); // 缓存1年
      res.send(imageBuffer);
    } catch (error) {
      throw new NotFoundException('图片文件读取失败');
    }
  }
} 